package org.csu.onlineedubackend.service.impl;

import org.csu.onlineedubackend.entity.*;
import org.csu.onlineedubackend.mapper.*;
import org.csu.onlineedubackend.entity.ChatMessage;
import org.csu.onlineedubackend.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.*;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ConversationMapper conversationMapper;
    
    @Autowired
    private MessageMapper messageMapper;
    
    @Autowired
    private ConversationParticipantMapper participantMapper;
    
    @Autowired
    private ChatGroupMapper chatGroupMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GroupAdminMapper groupAdminMapper;

    @Override
    @Transactional
    public Conversation createPrivateConversation(Integer userId1, Integer userId2) {
        // 检查是否已存在私聊会话
        Conversation existingConversation = conversationMapper.findPrivateConversation(userId1, userId2);
        if (existingConversation != null) {
            return existingConversation;
        }
        
        // 创建新的私聊会话
        Conversation conversation = new Conversation();
        conversation.setType("PRIVATE");
        conversationMapper.insert(conversation);
        
        // 添加参与者
        ConversationParticipant participant1 = new ConversationParticipant();
        participant1.setConversationId(conversation.getId());
        participant1.setUserId(userId1);
        participant1.setUnreadCount(0);
        participantMapper.insert(participant1);
        
        ConversationParticipant participant2 = new ConversationParticipant();
        participant2.setConversationId(conversation.getId());
        participant2.setUserId(userId2);
        participant2.setUnreadCount(0);
        participantMapper.insert(participant2);
        
        return conversation;
    }

    @Override
    @Transactional
    public Conversation createGroupConversation(String groupName, Integer ownerId, List<Integer> memberIds) {
        // 创建群聊会话
        Conversation conversation = new Conversation();
        conversation.setType("GROUP");
        conversationMapper.insert(conversation);
        
        // 创建群组信息
        ChatGroup chatGroup = new ChatGroup();
        chatGroup.setConversationId(conversation.getId());
        chatGroup.setName(groupName);
        chatGroup.setOwnerId(ownerId);
        chatGroupMapper.insert(chatGroup);
        
        // 添加所有成员作为参与者
        Set<Integer> uniqueMembers = new HashSet<>(memberIds);
        uniqueMembers.add(ownerId); // 确保群主也是成员
        
        for (Integer userId : uniqueMembers) {
            ConversationParticipant participant = new ConversationParticipant();
            participant.setConversationId(conversation.getId());
            participant.setUserId(userId);
            participant.setUnreadCount(0);
            participantMapper.insert(participant);
        }
        
        return conversation;
    }

    @Override
    public List<Map<String, Object>> getUserConversations(Integer userId) {
        List<Conversation> conversations = conversationMapper.findByUserId(userId);
        List<Map<String, Object>> result = new ArrayList<>();
        
        for (Conversation conversation : conversations) {
            Map<String, Object> conversationData = new HashMap<>();
            conversationData.put("conversation", conversation);
            
            // 获取最后一条消息
            Message lastMessage = messageMapper.findLastMessageByConversationId(conversation.getId());
            if (lastMessage != null) {
                // 获取发送者信息
                User sender = userMapper.findById(lastMessage.getSenderId());
                
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setId(lastMessage.getId());
                chatMessage.setConversationId(lastMessage.getConversationId());
                chatMessage.setSenderId(lastMessage.getSenderId());
                chatMessage.setSenderName(sender != null ? sender.getName() : "未知用户");
                chatMessage.setContent(lastMessage.getContent());
                chatMessage.setCreatedAt(lastMessage.getCreatedAt());

                chatMessage.setMessageType(lastMessage.getMessageType());
                chatMessage.setDuration(lastMessage.getDuration());
                
                conversationData.put("lastMessage", chatMessage);
            }
            
            // 获取未读消息数
            ConversationParticipant participant = participantMapper.findByConversationAndUser(
                    conversation.getId(), userId);
            conversationData.put("unreadCount", participant != null ? participant.getUnreadCount() : 0);
            
            // 根据会话类型获取不同的信息
            if ("PRIVATE".equals(conversation.getType())) {
                // 私聊：获取对方信息
                List<User> participants = participantMapper.findParticipantsByConversationId(conversation.getId());
                User otherUser = null;
                for (User user : participants) {
                    if (!user.getId().equals(userId)) {
                        otherUser = user;
                        break;
                    }
                }
                
                if (otherUser != null) {
                    conversationData.put("title", otherUser.getName());
                    conversationData.put("avatar", otherUser.getName().substring(0, 1)); // 取名字首字母作为头像
                    conversationData.put("targetUser", otherUser);
                }
            } else if ("GROUP".equals(conversation.getType())) {
                // 群聊：获取群组信息
                ChatGroup chatGroup = chatGroupMapper.findByConversationId(conversation.getId());
                if (chatGroup != null) {
                    conversationData.put("title", chatGroup.getName());
                    conversationData.put("avatar", chatGroup.getName().substring(0, 1)); // 取群名首字母作为头像
                    conversationData.put("group", chatGroup);
                }
            }
            
            result.add(conversationData);
        }
        
        // 按最后更新时间排序
        result.sort((a, b) -> {
            Conversation convA = (Conversation) a.get("conversation");
            Conversation convB = (Conversation) b.get("conversation");
            return convB.getUpdatedAt().compareTo(convA.getUpdatedAt());
        });
        
        return result;
    }

    @Override
    public List<ChatMessage> getConversationMessages(Long conversationId, Integer userId, int page, int size) {
        // 检查用户是否是会话的参与者
        ConversationParticipant participant = participantMapper.findByConversationAndUser(conversationId, userId);
        if (participant == null) {
            throw new RuntimeException("用户不是该会话的参与者");
        }
        
        // 计算分页参数
        int offset = page * size;
        
        // 获取消息
        List<Message> messages = messageMapper.findByConversationId(conversationId, offset, size);
        List<ChatMessage> chatMessages = new ArrayList<>();
        
        for (Message message : messages) {
            User sender = userMapper.findById(message.getSenderId());
            
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setId(message.getId());
            chatMessage.setConversationId(message.getConversationId());
            chatMessage.setSenderId(message.getSenderId());
            chatMessage.setSenderName(sender != null ? sender.getName() : "未知用户");
            chatMessage.setContent(message.getContent());
            chatMessage.setCreatedAt(new Date(message.getCreatedAt().getTime()));
            
            // 添加缺失的字段映射
            chatMessage.setMessageType(message.getMessageType());
            chatMessage.setDuration(message.getDuration());
            
            chatMessages.add(chatMessage);
        }
        
        // 标记为已读
        markAsRead(conversationId, userId);
        
        return chatMessages;
    }

    @Override
    @Transactional
    public ChatMessage sendMessage(ChatMessage chatMessage) {
        // 创建消息实体
        Message message = new Message();
        message.setConversationId(chatMessage.getConversationId());
        message.setSenderId(chatMessage.getSenderId());
        message.setContent(chatMessage.getContent());
        message.setCreatedAt(new Timestamp(System.currentTimeMillis()));

        // 设置消息类型和时长
        if (chatMessage.getMessageType() != null) {
            message.setMessageType(chatMessage.getMessageType());
        } else {
            message.setMessageType("TEXT"); // 默认为文本
        }
        message.setDuration(chatMessage.getDuration());
        
        // 保存消息
        messageMapper.insert(message);
        
        // 更新会话的最后一条消息
        conversationMapper.updateLastMessage(chatMessage.getConversationId(), message.getId());
        
        // 更新其他参与者的未读消息计数
        participantMapper.incrementUnreadCount(chatMessage.getConversationId(), chatMessage.getSenderId());
        
        // 设置消息ID和发送时间
        chatMessage.setId(message.getId());
        chatMessage.setCreatedAt(new Date(message.getCreatedAt().getTime()));
        
        // 获取发送者信息
        User sender = userMapper.findById(chatMessage.getSenderId());
        if (sender != null) {
            chatMessage.setSenderName(sender.getName());
        }
        
        return chatMessage;
    }

    @Override
    public void markAsRead(Long conversationId, Integer userId) {
        participantMapper.resetUnreadCount(conversationId, userId);
    }

    @Override
    public List<User> getConversationParticipants(Long conversationId) {
        return participantMapper.findParticipantsByConversationId(conversationId);
    }

    @Override
    @Transactional
    public void addUserToGroup(Long groupId, Integer userId) {
        ChatGroup chatGroup = chatGroupMapper.findById(groupId);
        if (chatGroup == null) {
            throw new RuntimeException("群组不存在");
        }
        
        // 检查用户是否已在群组中
        ConversationParticipant existingParticipant = participantMapper.findByConversationAndUser(
                chatGroup.getConversationId(), userId);
        if (existingParticipant != null) {
            return; // 用户已在群组中
        }
        
        // 添加用户到群组
        ConversationParticipant participant = new ConversationParticipant();
        participant.setConversationId(chatGroup.getConversationId());
        participant.setUserId(userId);
        participant.setUnreadCount(0);
        participantMapper.insert(participant);
    }

    @Override
    @Transactional
    public void removeUserFromGroup(Long groupId, Integer userId) {
        ChatGroup chatGroup = chatGroupMapper.findById(groupId);
        if (chatGroup == null) {
            throw new RuntimeException("群组不存在");
        }
        
        // 检查是否是群主
        if (chatGroup.getOwnerId().equals(userId)) {
            throw new RuntimeException("群主不能退出群聊，请先转让群主或解散群聊");
        }
        
        // 从管理员列表中移除(如果是管理员)
        groupAdminMapper.deleteByGroupAndUser(groupId, userId);
        
        // 从会话参与者中移除用户
        participantMapper.deleteByConversationAndUser(chatGroup.getConversationId(), userId);
    }

    @Override
    public Map<Long, Integer> getUnreadMessageCounts(Integer userId) {
        // 获取用户的所有会话
        List<Conversation> conversations = conversationMapper.findByUserId(userId);
        
        Map<Long, Integer> unreadCounts = new HashMap<>();
        for (Conversation conversation : conversations) {
            ConversationParticipant participant = participantMapper.findByConversationAndUser(
                    conversation.getId(), userId);
            if (participant != null) {
                unreadCounts.put(conversation.getId(), participant.getUnreadCount());
            }
        }
        
        return unreadCounts;
    }

    @Override
    @Transactional
    public boolean deleteConversation(Long conversationId, Integer userId) {
        // 检查用户是否是会话的参与者
        ConversationParticipant participant = participantMapper.findByConversationAndUser(conversationId, userId);
        if (participant == null) {
            return false; // 用户不是该会话的参与者
        }
        
        // 对于临时会话，只需要删除该用户的参与者记录
        // 保留会话及其消息，以便其他参与者仍然可以访问
        participantMapper.deleteByConversationAndUser(conversationId, userId);
        
        // 检查会话是否还有其他参与者
        List<User> remainingParticipants = participantMapper.findParticipantsByConversationId(conversationId);
        
        // 如果没有其他参与者，则删除整个会话及其消息
        if (remainingParticipants.isEmpty()) {
            // 删除所有相关消息
            messageMapper.deleteByConversationId(conversationId);
            
            // 如果是群聊，删除群组信息
            ChatGroup chatGroup = chatGroupMapper.findByConversationId(conversationId);
            if (chatGroup != null) {
                // 删除所有管理员记录
                groupAdminMapper.deleteByGroupId(chatGroup.getId());
                // 删除群组
                chatGroupMapper.deleteById(chatGroup.getId());
            }
            
            // 删除会话
            conversationMapper.deleteById(conversationId);
        }
        
        return true;
    }
} 